﻿using MeetingAssistant.Component.Data.Enum;
using MeetingAssistant.Component.Tools;
using MeetingAssistant.Component.Tools.helpers;
using MeetingAssistant.CoreBLL.Service.Member.Interface;
using MeetingAssistant.Domain.Model.Member;
using MeetingAssistant.ViewModel.Member;
using MeetingAssistant.Web.Extension.Common;
using MeetingAssistant.Web.Extension.Filters;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace MeetingAssistant.Areas.Member.Controllers
{
    public class CompanyController : Controller
    {
        private readonly ICompanyService _companyService;

        public CompanyController(ICompanyService companyService)
        {
            this._companyService = companyService;
        }

        // GET: Member/Company
        [Layout]
        public ActionResult Index()
        {
            GetButtonPermissions();
            var enabledItems = DataSourceHelper.GetIsTrue();
            ViewBag.EnableItems = enabledItems;
            return View();
        }

        /// <summary>
        /// 获取公司信息
        /// </summary>
        /// <param name="limit"></param>
        /// <param name="offset"></param>
        /// <param name="companyName"></param>
        /// <param name="enable"></param>
        /// <returns></returns>
        public JsonResult GetCompanys(int limit, int offset, string companyName, int enable)
        {
            int total = 0;
            Expression<Func<Company, bool>> wh = c => true;
            if (!string.IsNullOrEmpty(companyName))
            {
                wh = wh.And(c => c.CompanyName.Contains(companyName.Trim()));
            }
            if (enable >= 0)
            {
                var yesOrNot = enable != 0;
                wh = wh.And(c => c.Enabled == yesOrNot);
            }
            var result = _companyService.GetListCompanyVM(wh, limit, offset, out total);
            return Json(new { total = total, rows = result }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult Create()
        {
            var model = new CompanyVM();
            return PartialView(model);
        }
        
        [HttpPost]
        public ActionResult Create(CompanyVM companyVM)
        {
            if (!ModelState.IsValid)
                return Json(new OperationResult(OperationResultType.ParamError, "参数错误，请重新输入！"));
            var result = _companyService.Insert(companyVM);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        /// <summary>
        /// 打开修改框
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [IsAjax]
        public ActionResult Edit(int id = 0)
        {
            var company = _companyService.Companys.FirstOrDefault(c => c.Id == id);
            if (company == null)
                return PartialView("Create", new UserVM());
            var model = new CompanyVM()
            {
                Id = company.Id,
                CompanyName = company.CompanyName,
                CompanyAddress = company.CompanyAddress,
                Code = company.Code,
                Enabled = company.Enabled,
            };
            return PartialView("Create", model);
        }
        [HttpPost]
        public ActionResult Edit(CompanyVM companyVM)
        {
            ValidationHelper.RemoveValidationError(ModelState, "Password");
            if (!ModelState.IsValid)
                return Json(new OperationResult(OperationResultType.ParamError, "参数错误，请重新输入！"));
            var result = _companyService.Update(companyVM);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        [HttpPost]
        public ActionResult Delete()
        {
            var companylist = Request.Form["arrselections"];
            IEnumerable<CompanyVM> list = JsonConvert.DeserializeObject<List<CompanyVM>>(companylist);
            var result = _companyService.Delete(list);
            result.Message = result.Message ?? result.ResultType.GetDescription();
            return Json(result);
        }

        #region 私有函数 获取按钮可见权限
        [NonAction]
        private void GetButtonPermissions()
        {
            string userId = ((System.Web.Security.FormsIdentity)(HttpContext.User.Identity)).Ticket.UserData;
            List<Permission> permissionCache =
                (List<Permission>)CacheHelper.GetCache(CacheKey.StrPermissionsByUid + "_" + userId);
            //新增按钮
            Permission addCompanyButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.AddCompany.ToString());
            ViewBag.AddCompanyButton = addCompanyButton;
            //修改按钮
            Permission updateCompanyButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.UpdateCompany.ToString());
            ViewBag.UpdateCompanyButton = updateCompanyButton;
            //删除按钮
            Permission deleteCompanyButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.DeleteCompany.ToString());
            ViewBag.DeleteCompanyButton = deleteCompanyButton;
            Permission uploadCompanyButton =
                permissionCache.FirstOrDefault(c => c.Enabled == true && c.Code == EnumPermissionCode.UploadCompany.ToString());
            ViewBag.UploadCompanyButton = uploadCompanyButton;
        }
        #endregion
    }
}